// SPDX-License-Identifier: GPL-2.0
/*
 * ov13850 driver
 *
 * Copyright (C) 2017 Fuzhou Rockchip Electronics Co., Ltd.
 *
 * V0.0X01.0X01 add poweron function.
 * V0.0X01.0X02 fix mclk issue when probe multiple camera.
 * V0.0X01.0X03 add enum_frame_interval function.
 */

#include <linux/clk.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/gpio/consumer.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <linux/regulator/consumer.h>
#include <linux/sysfs.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <linux/rk-camera-module.h>
#include <media/media-entity.h>
#include <media/v4l2-async.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-subdev.h>
#include <linux/pinctrl/consumer.h>

#include "lt9211_bj_pal.h"

#define DRIVER_VERSION			KERNEL_VERSION(0, 0x01, 0x03)
#define OV13850_LANES   4

#define lt9211_dbgen

#ifdef lt9211_dbgen
#define lt9211_dbg(dev,...)    dev_info(dev,__VA_ARGS__)   
#else
#define lt9211_dbg(dev)  
#endif

#define OV13850_LINK_FREQ_300MHZ	500000000
/* pixel rate = link frequency * 2 * lanes / BITS_PER_SAMPLE */
//#define OV13850_PIXEL_RATE		(OV13850_LINK_FREQ_300MHZ * 2 * 2 / 10)
#define OV13850_PIXEL_RATE		(OV13850_LINK_FREQ_300MHZ  / 10)
#define OV13850_XVCLK_FREQ		24000000




#define OV13850_NAME			"ov13850b"
#define OV13850_VTS_MAX         0x7fff
#define cam_width 720 
#define cam_height 288

static u8 ver = 0;
static u8 sync_polarity;
static u8 vs;
static u8 hs[2];
static u8 vbp;
static u8 vfp;
static u8 hbp[2];
static u8 hfp[2];
static u8 vtotal[2];
static u8 htotal[2];
static u8 vact[2];
static u8 hact[2];


struct ov13850bb_mode {
	u32 width;
	u32 height;
	struct v4l2_fract max_fps;
	u32 hts_def;
	u32 vts_def;
	u32 exp_def;

};
struct ov13850b {
	struct i2c_client	*client;
	struct clk		*xvclk;
	struct gpio_desc	*reset_gpio;
	struct gpio_desc	*pwdn_gpio;


	struct pinctrl		*pinctrl;
	struct pinctrl_state	*pins_default;
	struct pinctrl_state	*pins_sleep;

	struct v4l2_subdev	subdev;
	struct media_pad	pad;
	struct v4l2_ctrl_handler ctrl_handler;
	struct v4l2_ctrl	*exposure;
	struct v4l2_ctrl	*anal_gain;
	struct v4l2_ctrl	*digi_gain;
	struct v4l2_ctrl	*hblank;
	struct v4l2_ctrl	*vblank;
	struct v4l2_ctrl	*test_pattern;
	struct mutex		mutex;
	bool			streaming;
	bool			power_on;
	const struct ov13850bb_mode *cur_mode;
	u32			module_index;
	const char		*module_facing;
	const char		*module_name;
	const char		*len_name;
};

#define to_ov13850b(sd) container_of(sd, struct ov13850b, subdev)



static const struct ov13850bb_mode supported_modes[] = {
	{
		.width = cam_width,
		.height = cam_height,
		.max_fps = {
			.numerator = 10000,
			.denominator = 600000,
		},
		.exp_def = 1546,
		.hts_def = 720,
		.vts_def = 312,
		//.vts_def = 625,
	},
};

static const s64 link_freq_menu_items[] = {
	OV13850_LINK_FREQ_300MHZ
};
static int ov13850b_write_reg(struct i2c_client *client, u8 reg, u8 val)
{

    //int ret;
    struct i2c_msg msg;
    u8 buf[2];
    buf[0] = reg;
    buf[1] = val;

    msg.addr = client->addr;
    msg.flags = 0;
    msg.len = 2;
    msg.buf = buf;
#if 0
    ret = i2c_transfer(client->adapter, &msg, 1);
    if (ret < 0) {
    dev_err(&client->dev, "Failed writing register 0x%04x!\n", reg);
    return -EIO;
    }
#endif
#if 1
	if (i2c_master_send(client, buf, 2) != 2)
    {
        dev_err(&client->dev, "Failed writing register 0x%04x!\n", reg);
        return -EIO;
    }
#endif


	//lt9211_dbg(&client->dev,"w:%x to reg:%x\n",val,reg);
	
	return 0;
}
static int ov13850b_read_reg(struct i2c_client *client, u8 reg,u8 *val)
{
	struct i2c_msg msgs[2];
	u8 buf;

	int ret;

	msgs[0].addr = client->addr;
	msgs[0].flags = 0;
	msgs[0].len = 1;
	msgs[0].buf = &reg;

	msgs[1].addr = client->addr;
	msgs[1].flags = I2C_M_RD;
	msgs[1].len = 1;
	msgs[1].buf = &buf;
#if 1
	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
	if (ret <0 ){
		dev_err(&client->dev, "Failed read register 0x%04x!\n", reg);
		return -EIO;
	}

	*val = buf;
#endif
	return 0;
}


static int ov13850b_write_array(struct i2c_client *client,
			       const struct regval *regs)
{
	u32 i;
	int ret = 0;

	for (i = 0; ret == 0 && regs[i].addr != REG_NULL; i++)
	{
		
		ret = ov13850b_write_reg(client, regs[i].addr,regs[i].val);
	}
	return ret;
}




static int ov13850b_enum_mbus_code(struct v4l2_subdev *sd,
				  struct v4l2_subdev_pad_config *cfg,
				  struct v4l2_subdev_mbus_code_enum *code)
{
	//struct ov13850b *ov13850b = to_ov13850b(sd);
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	if (code->index != 0)
		return -EINVAL;
	code->code = MEDIA_BUS_FMT_RGB888_1X24;
	//code->code = MEDIA_BUS_FMT_YUYV8_2X8;

	return 0;
}
static int ov13850b_enum_frame_sizes(struct v4l2_subdev *sd,
				    struct v4l2_subdev_pad_config *cfg,
				   struct v4l2_subdev_frame_size_enum *fse)
{
	//struct ov13850b *ov13850b = to_ov13850b(sd);
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	if (fse->index >= ARRAY_SIZE(supported_modes))
		return -EINVAL;

	if (fse->code != MEDIA_BUS_FMT_RGB888_1X24)
	//if (fse->code != MEDIA_BUS_FMT_YUYV8_2X8)
		return -EINVAL;

	fse->min_width  = cam_width;
	fse->max_width  = cam_width;
	fse->max_height = cam_height;
	fse->min_height = cam_height;

	return 0;
}
static int ov13850b_enum_frame_interval(struct v4l2_subdev *sd,
				       struct v4l2_subdev_pad_config *cfg,
				       struct v4l2_subdev_frame_interval_enum *fie)
{
	//struct ov13850b *ov13850b = to_ov13850b(sd);
//	dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	if (fie->index >= ARRAY_SIZE(supported_modes))
		return -EINVAL;

	if (fie->code != MEDIA_BUS_FMT_RGB888_1X24)
	//if (fie->code != MEDIA_BUS_FMT_YUYV8_2X8)
		return -EINVAL;

	fie->width = cam_width;
	fie->height = cam_height;
	fie->interval = supported_modes[0].max_fps;
	return 0;
}

static int ov13850b_set_fmt(struct v4l2_subdev *sd,
			   struct v4l2_subdev_pad_config *cfg,
			  struct v4l2_subdev_format *fmt)
{
	struct ov13850b *ov13850b = to_ov13850b(sd);
	//const struct ov13850bb_mode *mode = ov13850b->cur_mode;

	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	mutex_lock(&ov13850b->mutex);

	
	fmt->format.code = MEDIA_BUS_FMT_RGB888_1X24;
	//fmt->format.code = MEDIA_BUS_FMT_YUYV8_2X8;
	fmt->format.width = cam_width;
	fmt->format.height = cam_height;
	fmt->format.field = V4L2_FIELD_NONE;
	//fmt->format.field = V4L2_FIELD_INTERLACED;

  	mutex_unlock(&ov13850b->mutex);

	return 0;
}

static int ov13850b_get_fmt(struct v4l2_subdev *sd,
			   struct v4l2_subdev_pad_config *cfg,
			   struct v4l2_subdev_format *fmt)
{
	struct ov13850b *ov13850b = to_ov13850b(sd);
	//const struct ov13850bb_mode *mode = ov13850b->cur_mode;

//	dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	mutex_lock(&ov13850b->mutex);
	{
		fmt->format.width = cam_width;
		fmt->format.height = cam_height;
		fmt->format.code = MEDIA_BUS_FMT_RGB888_1X24;
		//fmt->format.code = MEDIA_BUS_FMT_YUYV8_2X8;
		fmt->format.field = V4L2_FIELD_NONE;
	    //fmt->format.field = V4L2_FIELD_INTERLACED;
	}
	mutex_unlock(&ov13850b->mutex);

	return 0;
}


static int ov13850b_g_frame_interval(struct v4l2_subdev *sd,
				    struct v4l2_subdev_frame_interval *fi)
{
	struct ov13850b *ov13850b = to_ov13850b(sd);
	const struct ov13850bb_mode *mode = ov13850b->cur_mode;
	//dev_info(&ov13850b->client->dev,"%s %d add\n",__func__,__LINE__);

	mutex_lock(&ov13850b->mutex);
	fi->interval = mode->max_fps;
	mutex_unlock(&ov13850b->mutex);

	return 0;
}

static void ov13850b_get_module_inf(struct ov13850b *ov13850b,
				   struct rkmodule_inf *inf)
{
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	memset(inf, 0, sizeof(*inf));
	strlcpy(inf->base.sensor, OV13850_NAME, sizeof(inf->base.sensor));
	strlcpy(inf->base.module, ov13850b->module_name,
		sizeof(inf->base.module));
	strlcpy(inf->base.lens, ov13850b->len_name, sizeof(inf->base.lens));
}

static long ov13850b_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
	struct ov13850b *ov13850b = to_ov13850b(sd);
	long ret = 0;

	switch (cmd) {
	case RKMODULE_GET_MODULE_INFO:
		ov13850b_get_module_inf(ov13850b, (struct rkmodule_inf *)arg);
		break;
	default:
		ret = -ENOIOCTLCMD;
		break;
	}

	return ret;
}

#ifdef CONFIG_COMPAT
static long ov13850b_compat_ioctl32(struct v4l2_subdev *sd,
				   unsigned int cmd, unsigned long arg)
{
	void __user *up = compat_ptr(arg);
	struct rkmodule_inf *inf;
	struct rkmodule_awb_cfg *cfg;
	long ret;

	switch (cmd) {
	case RKMODULE_GET_MODULE_INFO:
		inf = kzalloc(sizeof(*inf), GFP_KERNEL);
		if (!inf) {
			ret = -ENOMEM;
			return ret;
		}

		ret = ov13850b_ioctl(sd, cmd, inf);
		if (!ret)
			ret = copy_to_user(up, inf, sizeof(*inf));
		kfree(inf);
		break;
	case RKMODULE_AWB_CFG:
		cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
		if (!cfg) {
			ret = -ENOMEM;
			return ret;
		}

		ret = copy_from_user(cfg, up, sizeof(*cfg));
		if (!ret)
			ret = ov13850b_ioctl(sd, cmd, cfg);
		kfree(cfg);
		break;
	default:
		ret = -ENOIOCTLCMD;
		break;
	}

	return ret;
}
#endif


static int LT9211_ChipID(struct ov13850b *ov13850b)
{
	u8 val[4] = {0,0,0,0};

	if(ov13850b_write_reg(ov13850b->client,0xff,	0x81))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x00,&val[0]))
		return -EIO; 
	if(ov13850b_read_reg(ov13850b->client,0x01,&val[1]))
		return -EIO; 
	if(ov13850b_read_reg(ov13850b->client,0x02,&val[2]))
		return -EIO; 
	//lt9211_dbg(&ov13850b->client->dev,"LT9211 Chip ID:%x.%x.%x\n",val[0],val[1],val[2]);
	if(ov13850b_read_reg(ov13850b->client,0x02,&ver))
		return -EIO; 
	return 0;
}


static int  LT9211_SystemInt(struct ov13850b *ov13850b)
{
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	return ov13850b_write_array(ov13850b->client, LT9211_SystemInt_regs);
	
}


static int LT9211_TTLRxPhy(struct ov13850b *ov13850b)
{
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_array(ov13850b->client, LT9211_TTLRxPhy_regs0))
		return -EIO;
    /*
	if(ver == 0xe4)
	{
		if(ov13850b_write_reg(ov13850b->client,0x63,	0xff))
			return -EIO;
	}
	else
	{
		if(ov13850b_write_reg(ov13850b->client,0x63,	0x00))
			return -EIO;
	}
    */
	if(ov13850b_write_array(ov13850b->client, LT9211_TTLRxPhy_regs1))
        return -EIO;
    /* enable bt1120 input */ 
    /*
    if(ov13850b_read_reg(ov13850b->client,0x48,&val))
        return -EIO;    
    if(ov13850b_write_reg(ov13850b->client,0x48,	val|0x2))
		return -EIO;
    if(ov13850b_read_reg(ov13850b->client,0x48,&val))
        return -EIO;    
    printk("lt9211 bt1120 0x%x \n",val);
    */
    return 0;
	
}

static int LT9211_SetVideoTiming(struct ov13850b *ov13850b)
{
   u16 hact = 720;
   u16 hfp = 16;
   u16 hs = 62;
   u16 vfp = 9;
   u16 vs = 6;
   if(ov13850b_write_reg(ov13850b->client,0xff,	0x85))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x20,(u8)((hact*2)>>8)))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x21,(u8)((hact*2))))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x22,(u8)((hfp*2)>>8)))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x23,(u8)((hfp*2))))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x24,(u8)((hs*2)>>8)))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x25,(u8)((hs*2))))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x38,(u8)((vfp*2)>>8)))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x39,(u8)((vfp*2))))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x3c,(u8)((vs*2)>>8)))
        return -EIO;
   if(ov13850b_write_reg(ov13850b->client,0x3d,(u8)((vs*2))))
        return -EIO;

   return 0;
}

static int LT9211_BTVideoCheck(struct ov13850b *ov13850b)
{
    u8 val;
    u16 h_act;
                    
    if(ov13850b_write_reg(ov13850b->client,0xff,	0x86))
      return -EIO;
    if(ov13850b_write_reg(ov13850b->client,0x20,	0x33))
      return -EIO;
	msleep(100);

    if(ov13850b_write_reg(ov13850b->client,0xff,	0x85))
      return -EIO;
    while(1) {
	    val = 0;
	    if(ov13850b_read_reg(ov13850b->client,0x4f,(u8*)&val))
		    return -EIO;
        if(val&0x20){
            lt9211_dbg(&ov13850b->client->dev,"bt656 flag is set\n");
            if(ov13850b_write_reg(ov13850b->client,0xff,0x86)) {
                return -EIO;
            }
	        if(ov13850b_read_reg(ov13850b->client,0x8b,&vact[1]))
		        return -EIO;
	        if(ov13850b_read_reg(ov13850b->client,0x8c,&vact[0]))
		        return -EIO;
	        if(ov13850b_read_reg(ov13850b->client,0x8d,&hact[1]))
		        return -EIO;
	        if(ov13850b_read_reg(ov13850b->client,0x8e,&hact[0]))
		        return -EIO;
            h_act = (*(u16*)hact - 4)/2;
            hact[1] = (h_act >>8)&0xFF;
            hact[0] = (h_act)&0xFF;

	        if(ov13850b_read_reg(ov13850b->client,0x8f,&htotal[1]))
		        return -EIO;
	        if(ov13850b_read_reg(ov13850b->client,0x90,&htotal[0]))
		        return -EIO;

            lt9211_dbg(&ov13850b->client->dev,"detected hact:%d htotal:%d vact:%d\n",
                                                    *(u16*)hact,*(u16*)htotal, *(u16*)vact);                                          
            LT9211_SetVideoTiming(ov13850b);
            break;
        }

    }
    return 0;
}


static int LT9211_ClkDetDebug(struct ov13850b *ov13850b)
{
	u32 val;
	u32 pixel_clock;
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_array(ov13850b->client, LT9211_ClkDetDebug_regs))
		return -EIO;
	
	msleep(100);
	
	val = 0;
	if(ov13850b_read_reg(ov13850b->client,0x08,(u8*)&val))
		return -EIO;
	pixel_clock = (val&0x0f)<<8;
	
	val = 0;
	if(ov13850b_read_reg(ov13850b->client,0x09,(u8*)&val))
		return -EIO;
	pixel_clock += val;
	pixel_clock = pixel_clock<<8;
	
	val = 0;
	if(ov13850b_read_reg(ov13850b->client,0x0a,(u8*)&val))
		return -EIO;
	pixel_clock += val;
	
	lt9211_dbg(&ov13850b->client->dev,"input ttlclk:%d\n",pixel_clock);
	return 0;
}


static int LT9211_VideoCheck(struct ov13850b *ov13850b)
{

    u8 val;
	
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_reg(ov13850b->client,0xff,0x86))
		return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x20,0x00))
		return -EIO;
	msleep(100);
	
	if(ov13850b_read_reg(ov13850b->client,0x70,&sync_polarity))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x71,&vs))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x72,&hs[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x73,&hs[0]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x74,&vbp))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x75,&vfp))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x76,&hbp[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x77,&hbp[0]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x78,&hfp[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x79,&hfp[0]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x7a,&vtotal[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x7b,&vtotal[0]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x7c,&htotal[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x7d,&htotal[0]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x7e,&vact[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x7f,&vact[0]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x80,&hact[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x81,&hact[0]))
		return -EIO;	
	
	if(!(sync_polarity & 0x01)) //hsync
	{
		if(ov13850b_write_reg(ov13850b->client,0xff,0x85))
			return -EIO;
        if(ov13850b_read_reg(ov13850b->client,0x47,&val))
			return -EIO;
		val = ((val) | 0x10);
		if(ov13850b_write_reg(ov13850b->client,0x47,val))
			return -EIO;
	}
	if(!(sync_polarity & 0x02)) //vsync
	{
       if(ov13850b_write_reg(ov13850b->client,0xff,0x85))
			return -EIO;
        if(ov13850b_read_reg(ov13850b->client,0x47,&val))
			return -EIO;
		val = ((val) | 0x20);
		if(ov13850b_write_reg(ov13850b->client,0x47,val))
			return -EIO; 
	}
	
	
	lt9211_dbg(&ov13850b->client->dev,"hfp:%d hs:%d hbp:%d hact:%d htotal:%d\n",
									*(u16*)hfp,*(u16*)hs,*(u16*)hbp,*(u16*)hact,*(u16*)htotal);
	lt9211_dbg(&ov13850b->client->dev,"vfp:%d vs:%d vbp:%d vact:%d vtotal:%d\n",
									vfp,vs,vbp,*(u16*)vact,*(u16*)vtotal);
	lt9211_dbg(&ov13850b->client->dev,"sync_polarity:%x\n",sync_polarity);
	
	
	return 0;
}

static int LT9211_MipiTxPhy(struct ov13850b *ov13850b)
{
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_array(ov13850b->client, LT9211_MipiTxPhy_regs0))
		return -EIO;
	msleep(10);
	
	return ov13850b_write_array(ov13850b->client, LT9211_MipiTxPhy_regs1);
}


static int LT9211_MipiTxpll(struct ov13850b *ov13850b)
{
	int loopx;
	u8 val[2] = {0,0};
		
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_array(ov13850b->client, LT9211_MipiTxpll_regs))
		return -EIO;
	for(loopx = 0; loopx < 10; loopx++)
	{
		if(ov13850b_write_reg(ov13850b->client,0xff,0x87))
			return -EIO;
		if(ov13850b_read_reg(ov13850b->client,0x1f,&val[0]))
			return -EIO;	
		if(val[0] & 0x80)
		{
			if(ov13850b_read_reg(ov13850b->client,0x20,&val[1]))
				return -EIO;		
			if(val[1] & 0x80)
			{
				lt9211_dbg(&ov13850b->client->dev,"LTxxx tx pll lock\n");
				return 0;
			}
			else
			{			
			}
			lt9211_dbg(&ov13850b->client->dev,"LTxxx tx pll cal done\n");
			return 0;
		}	
		else
		{		
		}
	}
	dev_err(&ov13850b->client->dev,"LTxxx tx pll always unlocked\n");
	return 0;
}


static int LT9211CSI_SetTxTiming(struct ov13850b *ov13850b)
{
    //u16 hact = 720;
    //u16 vbp = 30;
    //u16 vs = 6;
    //u16 vact = 480;
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_array(ov13850b->client, LT9211_SetTxTiming_regs0))
		return -EIO;
	
	if(ov13850b_write_reg(ov13850b->client,0x07,hact[1]))
			return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x08,hact[0]))
			return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x09,vs + vbp - 1))
			return -EIO;
	
	if(ov13850b_write_array(ov13850b->client, LT9211_SetTxTiming_regs1))
		return -EIO;
	
	if(ov13850b_write_reg(ov13850b->client,0x0c,vact[1]))
			return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x0d,vact[0]))
			return -EIO;
	
	return ov13850b_write_array(ov13850b->client, LT9211_SetTxTiming_regs2);
}


static int LT9211_MipiTxDigital(struct ov13850b *ov13850b)
{
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_array(ov13850b->client, LT9211_MipiTxDigital_regs))
        return -EIO;
    /*  csc funtion */
    
	if(ov13850b_write_reg(ov13850b->client,0xff,0xf9))
			return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x90,0x03))
			return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x91,0x03))
			return -EIO;
    
    return 0;
}
	

static int LT9211_DebugInfo(struct ov13850b *ov13850b)
{
	u8 val[4] = {0,0,0,0};
	
	//lt9211_dbg(&ov13850b->client->dev,"%s\n",__func__);
	if(ov13850b_write_reg(ov13850b->client,0xff,0x86))
			return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x00,0x12))
			return -EIO;
	msleep(100);
	
	if(ov13850b_read_reg(ov13850b->client,0x08,&val[2]))
		return -EIO;
	val[2] &= 0x0f;
	if(ov13850b_read_reg(ov13850b->client,0x09,&val[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x0a,&val[0]))
		return -EIO;
	
	lt9211_dbg(&ov13850b->client->dev,"mipi output byte clock:%d\n",*(u32*)val);

	if(ov13850b_write_reg(ov13850b->client,0xff,0x86))
			return -EIO;
	if(ov13850b_write_reg(ov13850b->client,0x00,0x0a))
			return -EIO;
	msleep(100);
	
	if(ov13850b_read_reg(ov13850b->client,0x08,&val[2]))
		return -EIO;
	val[2] &= 0x0f;
	if(ov13850b_read_reg(ov13850b->client,0x09,&val[1]))
		return -EIO;
	if(ov13850b_read_reg(ov13850b->client,0x0a,&val[0]))
		return -EIO;
	
	lt9211_dbg(&ov13850b->client->dev,"output pixclk:%d\n",*(u32*)val);
	return 0;
	
}
	
	
static int __ov13850b_start_stream(struct ov13850b *ov13850b)
{
	int ret;
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	ret = LT9211_ChipID(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_SystemInt(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_TTLRxPhy(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_ClkDetDebug(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_BTVideoCheck(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_VideoCheck(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_MipiTxPhy(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_MipiTxpll(ov13850b);
	if(ret)
		return ret;
	ret = LT9211CSI_SetTxTiming(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_MipiTxDigital(ov13850b);
	if(ret)
		return ret;
	ret = LT9211_DebugInfo(ov13850b);
	if(ret)
		return ret;
	
    return 0;
}

static int __ov13850b_stop_stream(struct ov13850b *ov13850b)
{
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);

    return 0;
}

static int ov13850b_s_stream(struct v4l2_subdev *sd, int on)
{
	struct ov13850b *ov13850b = to_ov13850b(sd);
	struct i2c_client *client = ov13850b->client;
	int ret = 0;

	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	mutex_lock(&ov13850b->mutex);
	on = !!on;
	if (on == ov13850b->streaming){
	    dev_info(&ov13850b->client->dev,"%s dev already opened\n",__func__);
		goto unlock_and_return;
    }

	if (on) {
		ret = pm_runtime_get_sync(&client->dev);
		if (ret < 0) {
	        dev_err(&ov13850b->client->dev,"%s pm runtime get sync faild\n",__func__);
			pm_runtime_put_noidle(&client->dev);
			goto unlock_and_return;
		}

		ret = __ov13850b_start_stream(ov13850b);
		if (ret) {
	        dev_err(&ov13850b->client->dev,"%s _start_stream faild\n",__func__);
			pm_runtime_put(&client->dev);
			goto unlock_and_return;
		}
	} else {
		__ov13850b_stop_stream(ov13850b);
		pm_runtime_put(&client->dev);
	}

	ov13850b->streaming = on;

unlock_and_return:
	mutex_unlock(&ov13850b->mutex);

	return ret;
}

static int ov13850b_s_power(struct v4l2_subdev *sd, int on)
{
	struct ov13850b *ov13850b = to_ov13850b(sd);
	struct i2c_client *client = ov13850b->client;
	int ret = 0;

	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	mutex_lock(&ov13850b->mutex);

	/* If the power state is not modified - no work to do. */
	if (ov13850b->power_on == !!on)
		goto unlock_and_return;

	if (on) {
		ret = pm_runtime_get_sync(&client->dev);
		if (ret < 0) {
	        dev_err(&ov13850b->client->dev,"%s pm runtime get sync faild\n",__func__);
			pm_runtime_put_noidle(&client->dev);
			goto unlock_and_return;
		}

		// i2c write

		ov13850b->power_on = true;
	} else {
		pm_runtime_put(&client->dev);
		ov13850b->power_on = false;
	}

unlock_and_return:
	mutex_unlock(&ov13850b->mutex);

	return ret;
}

/* Calculate the delay in us by clock rate and clock cycles */
static inline u32 ov13850b_cal_delay(u32 cycles)
{
	return DIV_ROUND_UP(cycles, OV13850_XVCLK_FREQ / 1000 / 1000);
}

static int __ov13850b_power_on(struct ov13850b *ov13850b)
{
	//int ret;
	u32 delay_us;
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	//struct device *dev = &ov13850b->client->dev;

	if (!IS_ERR(ov13850b->reset_gpio))
		gpiod_set_value_cansleep(ov13850b->reset_gpio, 0);

	usleep_range(500, 1000);
	
	/* 8192 cycles prior to first SCCB transaction */
	delay_us = ov13850b_cal_delay(8192);
	usleep_range(delay_us, delay_us * 2);

	return 0;

}

static void __ov13850b_power_off(struct ov13850b *ov13850b)
{
	//int ret;
	//struct device *dev = &ov13850b->client->dev;
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);


	if (!IS_ERR(ov13850b->reset_gpio))
		gpiod_set_value_cansleep(ov13850b->reset_gpio, 1);
	
}

static int ov13850b_runtime_resume(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct ov13850b *ov13850b = to_ov13850b(sd);
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);

	return __ov13850b_power_on(ov13850b);
}

static int ov13850b_runtime_suspend(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct ov13850b *ov13850b = to_ov13850b(sd);
	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);

	__ov13850b_power_off(ov13850b);

	return 0;
}

#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
static int ov13850b_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
	struct ov13850b *ov13850b = to_ov13850b(sd);
	struct v4l2_mbus_framefmt *try_fmt =
				v4l2_subdev_get_try_format(sd, fh->pad, 0);
	const struct ov13850bb_mode *def_mode = &supported_modes[0];

	//dev_info(&ov13850b->client->dev,"%s %d\n",__func__,__LINE__);
	mutex_lock(&ov13850b->mutex);
	/* Initialize try_fmt */
	try_fmt->width = def_mode->width;
	try_fmt->height = def_mode->height;
	try_fmt->code = MEDIA_BUS_FMT_RGB888_1X24;
	//try_fmt->code = MEDIA_BUS_FMT_YUYV8_2X8;
	try_fmt->field = V4L2_FIELD_NONE;
	//try_fmt->field = V4L2_FIELD_INTERLACED;

	mutex_unlock(&ov13850b->mutex);
	/* No crop or compose */

	return 0;
}
#endif

static int ov13850b_g_mbus_config(struct v4l2_subdev *sd, unsigned int pad_id,
				struct v4l2_mbus_config *config)
{
	u32 val = 0;

	val = 1 << (OV13850_LANES - 1) |
	      V4L2_MBUS_CSI2_CHANNEL_0 |
	      V4L2_MBUS_CSI2_CONTINUOUS_CLOCK;
	config->type = V4L2_MBUS_CSI2_DPHY;
	config->flags = val;

	return 0;
}																			 
static const struct dev_pm_ops ov13850b_pm_ops = {
	SET_RUNTIME_PM_OPS(ov13850b_runtime_suspend,
			   ov13850b_runtime_resume, NULL)
};

#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
static const struct v4l2_subdev_internal_ops ov13850b_internal_ops = {
	.open = ov13850b_open,
};
#endif

static const struct v4l2_subdev_core_ops ov13850b_core_ops = {
	.s_power = ov13850b_s_power,
	.ioctl = ov13850b_ioctl,
#ifdef CONFIG_COMPAT
	.compat_ioctl32 = ov13850b_compat_ioctl32,
#endif
};

static const struct v4l2_subdev_video_ops ov13850b_video_ops = {
	.s_stream = ov13850b_s_stream,
	.g_frame_interval = ov13850b_g_frame_interval,
};

static const struct v4l2_subdev_pad_ops ov13850b_pad_ops = {
	.enum_mbus_code = ov13850b_enum_mbus_code,
	.enum_frame_size = ov13850b_enum_frame_sizes,
	.enum_frame_interval = ov13850b_enum_frame_interval,
	.get_fmt = ov13850b_get_fmt,
	.set_fmt = ov13850b_set_fmt,
	.get_mbus_config = ov13850b_g_mbus_config,									  
};

static const struct v4l2_subdev_ops ov13850b_subdev_ops = {
	.core	= &ov13850b_core_ops,
	.video	= &ov13850b_video_ops,
	.pad	= &ov13850b_pad_ops,
};

static int ov13850b_set_ctrl(struct v4l2_ctrl *ctrl)
{
	struct ov13850b *ov13850b = container_of(ctrl->handler,
					     struct ov13850b, ctrl_handler);
	struct i2c_client *client = ov13850b->client;
	int ret = 0;

	if (pm_runtime_get(&client->dev) <= 0)
		return 0;

	switch (ctrl->id) {
	case V4L2_CID_VBLANK:
		break;
	default:
		dev_warn(&client->dev, "%s Unhandled id:0x%x, val:0x%x\n",
			 __func__, ctrl->id, ctrl->val);
		break;
	}

	pm_runtime_put(&client->dev);

	return ret;
}

static const struct v4l2_ctrl_ops ov13850b_ctrl_ops = {
	.s_ctrl = ov13850b_set_ctrl,
};

static int ov13850b_initialize_controls(struct ov13850b *ov13850b)
{
	const struct ov13850bb_mode *mode;
	struct v4l2_ctrl_handler *handler;
	struct v4l2_ctrl *ctrl;
	s64 vblank_def;
	u32 h_blank;
	int ret;

	handler = &ov13850b->ctrl_handler;
	mode = ov13850b->cur_mode;
	ret = v4l2_ctrl_handler_init(handler, 8);
	if (ret)
		return ret;
	handler->lock = &ov13850b->mutex;

	ctrl = v4l2_ctrl_new_int_menu(handler, NULL, V4L2_CID_LINK_FREQ,
				      0, 0, link_freq_menu_items);
	if (ctrl)
		ctrl->flags |= V4L2_CTRL_FLAG_READ_ONLY;

	v4l2_ctrl_new_std(handler, NULL, V4L2_CID_PIXEL_RATE,
			  0, OV13850_PIXEL_RATE, 1, OV13850_PIXEL_RATE);
 
	h_blank = mode->hts_def - mode->width;
	ov13850b->hblank = v4l2_ctrl_new_std(handler, NULL, V4L2_CID_HBLANK,
				h_blank, h_blank, 1, h_blank);
	if (ov13850b->hblank)
		ov13850b->hblank->flags |= V4L2_CTRL_FLAG_READ_ONLY;

	vblank_def = mode->vts_def - mode->height;
	ov13850b->vblank = v4l2_ctrl_new_std(handler, &ov13850b_ctrl_ops,
				V4L2_CID_VBLANK, vblank_def,
				OV13850_VTS_MAX - mode->height,
				1, vblank_def);

	if (handler->error) {
		ret = handler->error;
		dev_err(&ov13850b->client->dev,
			"Failed to init controls(%d)\n", ret);
		goto err_free_handler;
	}

	ov13850b->subdev.ctrl_handler = handler;

	return 0;

err_free_handler:
	v4l2_ctrl_handler_free(handler);

	return ret;
}

static int ov13850b_probe(struct i2c_client *client,
			 const struct i2c_device_id *id)
{
	struct device *dev = &client->dev;
	struct device_node *node = dev->of_node;
	struct ov13850b *ov13850b;
	struct v4l2_subdev *sd;
	char facing[2];
	int ret;

	dev_info(dev, "driver version: %02x.%02x.%02x",
		DRIVER_VERSION >> 16,
		(DRIVER_VERSION & 0xff00) >> 8,
		DRIVER_VERSION & 0x00ff);

	ov13850b = devm_kzalloc(dev, sizeof(*ov13850b), GFP_KERNEL);
	if (!ov13850b)
		return -ENOMEM;

	ret = of_property_read_u32(node, RKMODULE_CAMERA_MODULE_INDEX,
				   &ov13850b->module_index);
	ret |= of_property_read_string(node, RKMODULE_CAMERA_MODULE_FACING,
				       &ov13850b->module_facing);
	ret |= of_property_read_string(node, RKMODULE_CAMERA_MODULE_NAME,
				       &ov13850b->module_name);
	ret |= of_property_read_string(node, RKMODULE_CAMERA_LENS_NAME,
				       &ov13850b->len_name);
	if (ret) {
		dev_err(dev, "could not get module information!\n");
		return -EINVAL;
	}

	ov13850b->client = client;
	ov13850b->cur_mode = &supported_modes[0];


	ov13850b->reset_gpio = devm_gpiod_get(dev, "reset", GPIOD_OUT_LOW);
	if (IS_ERR(ov13850b->reset_gpio))
		dev_warn(dev, "Failed to get reset-gpios\n");

	mutex_init(&ov13850b->mutex);

	sd = &ov13850b->subdev;
	v4l2_i2c_subdev_init(sd, client, &ov13850b_subdev_ops);
	ret = ov13850b_initialize_controls(ov13850b);
	if (ret)
		goto err_destroy_mutex;

	ret = __ov13850b_power_on(ov13850b);
	if (ret)
		goto err_free_handler;


#ifdef CONFIG_VIDEO_V4L2_SUBDEV_API
	sd->internal_ops = &ov13850b_internal_ops;
	sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE;
#endif
#if defined(CONFIG_MEDIA_CONTROLLER)
	ov13850b->pad.flags = MEDIA_PAD_FL_SOURCE;
	sd->entity.function = MEDIA_ENT_F_CAM_SENSOR;
	ret = media_entity_pads_init(&sd->entity, 1, &ov13850b->pad);
	//sd->entity.type = MEDIA_ENT_T_V4L2_SUBDEV_SENSOR;
	//ret = media_entity_init(&sd->entity, 1, &ov13850b->pad, 0);
	if (ret < 0)
		goto err_power_off;
#endif

	memset(facing, 0, sizeof(facing));
	if (strcmp(ov13850b->module_facing, "back") == 0)
		facing[0] = 'b';
	else
		facing[0] = 'f';

	snprintf(sd->name, sizeof(sd->name), "m%02d_%s_%s %s",
		 ov13850b->module_index, facing,
		 OV13850_NAME, dev_name(sd->dev));
	ret = v4l2_async_register_subdev_sensor_common(sd);
	if (ret) {
		dev_err(dev, "v4l2 async register subdev failed\n");
		goto err_clean_entity;
	}

	pm_runtime_set_active(dev);
	pm_runtime_enable(dev);
	pm_runtime_idle(dev);

	return 0;

err_clean_entity:
#if defined(CONFIG_MEDIA_CONTROLLER)
	media_entity_cleanup(&sd->entity);
#endif
err_power_off:
	__ov13850b_power_off(ov13850b);
err_free_handler:
	v4l2_ctrl_handler_free(&ov13850b->ctrl_handler);
err_destroy_mutex:
	mutex_destroy(&ov13850b->mutex);

	return ret;
}

static int ov13850b_remove(struct i2c_client *client)
{
	struct v4l2_subdev *sd = i2c_get_clientdata(client);
	struct ov13850b *ov13850b = to_ov13850b(sd);

	v4l2_async_unregister_subdev(sd);
#if defined(CONFIG_MEDIA_CONTROLLER)
	media_entity_cleanup(&sd->entity);
#endif
	v4l2_ctrl_handler_free(&ov13850b->ctrl_handler);
	mutex_destroy(&ov13850b->mutex);

	pm_runtime_disable(&client->dev);
	if (!pm_runtime_status_suspended(&client->dev))
		__ov13850b_power_off(ov13850b);
	pm_runtime_set_suspended(&client->dev);

	return 0;
}

#if IS_ENABLED(CONFIG_OF)
static const struct of_device_id ov13850b_of_match[] = {
	{ .compatible = "ovti,ov13850bb" },
	{},
};
MODULE_DEVICE_TABLE(of, ov13850b_of_match);
#endif

static const struct i2c_device_id ov13850b_match_id[] = {
	{ "ovti,ov13850b", 0 },
	{ },
};

static struct i2c_driver ov13850b_i2c_driver = {
	.driver = {
		.name = OV13850_NAME,
		.pm = &ov13850b_pm_ops,
		.of_match_table = of_match_ptr(ov13850b_of_match),
	},
	.probe		= &ov13850b_probe,
	.remove		= &ov13850b_remove,
	.id_table	= ov13850b_match_id,
};

static int __init sensor_mod_init(void)
{
	return i2c_add_driver(&ov13850b_i2c_driver);
}

static void __exit sensor_mod_exit(void)
{
	i2c_del_driver(&ov13850b_i2c_driver);
}

device_initcall_sync(sensor_mod_init);
module_exit(sensor_mod_exit);

MODULE_DESCRIPTION("OmniVision ov13850b sensor driver");
MODULE_LICENSE("GPL v2");
